package cn.td0f7.android.wangzhongcourse.base;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.IOException;

import cn.td0f7.android.wangzhongcourse.entity.ProgressListener;
import cn.td0f7.android.wangzhongcourse.entity.ProgressModel;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

public class MyResponseBody extends ResponseBody {
    private ResponseBody responseBody;
    private ProgressListener listener;
    private BufferedSource bufferedSource;
    private Handler handler;

    public MyResponseBody(ResponseBody responseBody, ProgressListener listener) {
        this.responseBody = responseBody;
        this.listener = listener;
        if (handler == null)
            handler = new MyHandler();
    }

    private class MyHandler extends Handler {
        public MyHandler() {
            super(Looper.getMainLooper());
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ProgressModel model = (ProgressModel) msg.obj;
            if (listener != null) listener.onProgress(model);
        }
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();//总大小
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return responseBody.contentType();//类型
    }

    @NonNull
    @Override
    public BufferedSource source() {
        if (bufferedSource == null)
            bufferedSource = Okio.buffer(getSource(responseBody.source()));
        return bufferedSource;
    }

    private Source getSource(BufferedSource source) {
        return new ForwardingSource(source) {
            long total = 0;//下载总进度

            @Override
            public long read(@NonNull Buffer sink, long byteCount) throws IOException {
                long byteRead = super.read(sink, byteCount);//本次下载
                total += byteRead != -1 ? byteRead : 0;
                Message msg = handler.obtainMessage(1);
                msg.obj = new ProgressModel(total, contentLength(), total == contentLength());
                handler.sendMessage(msg);
                return byteRead;
            }
        };
    }
}
